package com.wuseguang.springcloud.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wuseguang.springcloud.dao.jdbc.PrizeJdbc;
import com.wuseguang.springcloud.dao.repository.PrizeClassRepository;
import com.wuseguang.springcloud.dao.repository.PrizeRepository;
import com.wuseguang.springcloud.dao.repository.StudentExchangeDetailsRepository;
import com.wuseguang.springcloud.dao.repository.StudentExchangeRecordRepository;
import com.wuseguang.springcloud.entity.Prize;
import com.wuseguang.springcloud.entity.PrizeClass;
import com.wuseguang.springcloud.entity.StudentExchangeDetails;
import com.wuseguang.springcloud.entity.StudentExchangeRecord;
import com.wuseguang.springcloud.service.PrizeService;
import com.wuseguang.springcloud.util.PaginationUtil;
import com.wuseguang.springcloud.util.PagingTool;
import com.wuseguang.springcloud.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 奖品表 服务实现类
 * </p>
 *
 * @author
 * @since 2020-06-19
 */
@Service
public class PrizeServiceImpl implements PrizeService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private PrizeJdbc prizeJdbc;
    @Autowired
    private PrizeRepository prizeRepository;
    @Autowired
    private PrizeClassRepository prizeClassRepository;
    @Autowired
    private StudentExchangeRecordRepository studentExchangeRecordRepository;
    @Autowired
    private StudentExchangeDetailsRepository studentExchangeDetailsRepository;

    @Override
    public Result addPrize(Prize prize) {
        logger.info("添加获取");
        //默认正常
        prize.setDel(0);
        Integer id = prizeRepository.save(prize).getId();
        //班级id
        String[] classId = prize.getClassIds().split(",");
        //循环班级id
        for (int i = 0; i < classId.length; i++) {
            //创建对象
            PrizeClass pc = new PrizeClass();
            pc.setClassId(Integer.valueOf(classId[i]));
            pc.setPrizeId(id);
            prizeClassRepository.save(pc);
        }

        return new Result();
    }

    @Override
    public Result findTeacherPrize(String teacherId, Integer indexNo, Integer rows) {
        logger.info("查询教师发布的活动");

        //查询教师发布的活动
        String sql = "select id,prize_name,prize_description,teacher_id ,points_required,stock,url" +
                " from prize where teacher_id = ? and del = 0 ORDER BY id desc";
        List<Map<String, Object>> list = prizeJdbc.queryListMap(sql, teacherId);

        //创建分页工具
        PagingTool tool = new PagingTool();
        //放入页码
        tool.setIndexNo(indexNo);
        //放入每页显示数量
        tool.setRows(rows);
        //放入角色集合
        tool.setList(list);
        //返回数据

        //没有查询的数据
        sql = "select  count(1) count from student_exchange_record ser " +
                "LEFT JOIN prize p ON ( p.id = ser.prize_id )   where p.teacher_id= ? and ser.whether  = 0";
        Integer count = prizeJdbc.queryCount(sql, teacherId);

        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("paginationData", new PaginationUtil(list.size(), rows, tool.getList(), indexNo));
        returnMap.put("notViewed", count);
        return new Result(returnMap);
    }

    @Override
    public Result findTeacherPrizeRecord(String teacherId, Integer indexNo, Integer rows) {

        logger.info("查询教师发布的活动兑换记录");
        //查询教师发布的活动兑换记录
        String sql = "select p.id, p.prize_name,p.prize_description,p.points_required,p.stock,p.url," +
                " ser.student_id,ser.student_name,c.`name` className,ser.state,DATE_FORMAT(ser.add_time,'%Y-%m-%d %T') add_time,ser.id recordId ,ser.whether " +
                " from student_exchange_record ser LEFT JOIN prize p ON ( p.id = ser.prize_id ) " +
                " left join   classes c on(ser.class_id=c.id) where p.teacher_id= ? ORDER BY ser.whether asc, ser.id desc";

        List<Map<String, Object>> list = prizeJdbc.queryListMap(sql, teacherId);

        //创建分页工具
        PagingTool tool = new PagingTool();
        //放入页码
        tool.setIndexNo(indexNo);
        //放入每页显示数量
        tool.setRows(rows);
        //放入角色集合
        tool.setList(list);
        //已查看的数据
        List<Map<String, Object>> listTwo = (List<Map<String, Object>>) tool.getList();

        if (listTwo.size() > 0) {
            //记录id
            String recordId = "";
            //循环获取记录id
            for (Map<String, Object> map : listTwo) {
                recordId += map.get("recordId") + ",";
            }
            recordId = recordId.substring(0, recordId.length() - 1);
            //把这些记录改为已看
            sql = "UPDATE `student_exchange_record` SET `whether` = 1 WHERE `id` in(" + recordId + ")";
            prizeJdbc.updateByParameter(sql);
        }
        //返回数据
        return new Result(new PaginationUtil<>(list.size(), rows, listTwo, indexNo));
    }

    @Override
    public Result updatePrizeRecordState(Integer recordId, Integer state) {

        //查询兑换信息
        StudentExchangeRecord ser = studentExchangeRecordRepository.findById(recordId).get();
        //0学生已兑换,1已撤销,2教师已确定
        if (state == 1) {
            logger.info("教师撤销学生兑换");
            //学生兑换详情
            StudentExchangeDetails sed = studentExchangeDetailsRepository.findByStudentId(ser.getStudentId());
            //奖品
            Prize prize = prizeRepository.findById(ser.getPrizeId()).get();
            //加回剩下积分
            sed.setFraction(sed.getFraction() + prize.getPointsRequired());
            //减掉已兑换数量
            sed.setPrizeNumber(sed.getPrizeNumber() - 1);
            //已兑换积分减少
            sed.setRedeemedPoints(sed.getRedeemedPoints() - prize.getPointsRequired());
            //库存加1
            prize.setStock(prize.getStock() + 1);
            //执行修改
            prizeRepository.save(prize);
            studentExchangeDetailsRepository.save(sed);
        }

        ser.setState(state);
        studentExchangeRecordRepository.save(ser);
        return new Result();
    }

    @Override
    public Result dismountPrize(Integer id) {
        Prize p = prizeRepository.findById(id).get();
        p.setDel(1);
        prizeRepository.save(p);
        return new Result();
    }

    @Override
    public Result viewRecords(Integer[] recordId) {

        List<StudentExchangeRecord> list = studentExchangeRecordRepository.findAllById(Arrays.asList(recordId));
        //修改list集合中的数据
        list.forEach(x -> x.setWhether(1));
        studentExchangeRecordRepository.saveAll(list);

        return new Result();
    }


    @Override
    public Result queryIntegral(String teacherId) {
        String sql = "SELECT fraction  FROM rating_limits_customized WHERE teacher_id=?";
        try {
            return new Result(prizeJdbc.queryMap(sql, teacherId));
        } catch (Exception e) {

        }
        return new Result();
    }
}
